package com.atguigu.gulistudy.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author hnb
 * @version 1.0
 * @Description:击中处理所有异常
 * @date 2021/10/28 下午9:18
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulistudy.product.controller")
public class GulistudyExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R HandleNotValidException(MethodArgumentNotValidException e) {
        //获取所有校验失败的字段
        List<FieldError> fieldErrors = e.getFieldErrors();
        //将提示结果放到map中
        Map<String, String> resmap = new HashMap<>();
        fieldErrors.forEach((fieldError) -> {
            String msg = fieldError.getDefaultMessage();
            String field = fieldError.getField();
            resmap.put(field, msg);
        });
        log.error("数据校验异常{},异常类型{}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", resmap);

    }

    @ExceptionHandler(value = Throwable.class)
    public R HandleException(Throwable throwable) {
        return R.error(BizCodeEnume.UNKONW_EXCEPTION.getCode(), BizCodeEnume.UNKONW_EXCEPTION.getMsg()).put("data", throwable.getMessage());
    }
}


